package com.shundr.user;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.shundr.R;
import com.shundr.base.BaseActivity;
import com.shundr.common.util.DialogUtil;
import com.shundr.common.util.JsonUtil;
import com.shundr.common.util.PrefConstants;
import com.shundr.common.util.PrefUtils;
import com.shundr.common.util.ProgressDialogHelper;
import com.shundr.common.util.ToastHelper;
import com.shundr.common.view.DialogDisplay.OnDisplayListener;
import com.shundr.frame.http.LHttpRequest;
import com.shundr.frame.util.StringUtil;
import com.shundr.user.http.UserRequest;
import com.shundr.user.model.UserInfo;
import com.shundr.user.util.UserUtil;

/**
 * 登录界面
 * LoginActivity
 * 
 * @author larry 2015-4-24 上午10:55:13 
 * @version 1.0.0
 *
 */
public class LoginActivity extends BaseActivity {
	private EditText etName;
	private EditText etPw;
	private Button btnNameClear;
	private Button btnPasswordClear;
	
	private Button btnForgetPassword;
	private Button btnLogin;
	
	private Handler mHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UserRequest.LOGIN_SUCCESSED:
				try {
					String data = msg.obj.toString();
					JSONObject obj = new JSONObject(data);
					String accessToken = obj.getString("accessToken");
					UserInfo user = JsonUtil.fromJson(obj.getJSONObject("user").toString(), UserInfo.class);
					if(user.getUserType() == 0){
						UserUtil.saveUserToLocal(mContext, user, accessToken);
						PrefUtils.setPrefString(mContext, PrefConstants.GET_WALLET_TIME, "");
						ProgressDialogHelper.dismiss();
						ToastHelper.toastShort(mContext, "登录成功");
						PrefUtils.setPrefString(mContext, PrefConstants.USER_PHONE, etName.getText().toString());
						if(user.getIdValidationStatus() == 0){//未认证
							DialogUtil.noticeAuthDialog(mContext, "认证", "您还未认证,认证后可无限制使用所有功能哦，现在去认证吧", "去认证", "以后再说", new OnDisplayListener() {
								
								@Override
								public void confirm() {
									startActivity(new Intent(mContext, UserAuthActivity.class));
									finish();
								}
								
								@Override
								public void cancel() {
									setResult(501);
									finish();
								}
							});
						}else{
							mHandler.postDelayed(new Runnable() {
								
								@Override
								public void run() {
									setResult(501);
									finish();
								}
							}, 1000);
						}
					}else{
						ProgressDialogHelper.dismiss();
						ToastHelper.toastShort(mContext, "抱歉，货主不能登录司机版客户端");
						etPw.setText("");
					}
				} catch (JSONException e) {
					e.printStackTrace();
					ProgressDialogHelper.dismiss();
				}
				break;
			case LHttpRequest.REQUEST_FAILED:
				ProgressDialogHelper.dismiss();
				ToastHelper.toastShort(mContext, msg.obj.toString());
				etPw.setText("");
				break;

			default:
				break;
			}
			super.handleMessage(msg);
		}
		
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		btnForgetPassword=(Button)findViewById(R.id.btn_set_password);
		btnForgetPassword.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				startActivity(new Intent(mContext, RetrievePasswordActivity.class));
			}
		});
		btnNameClear = (Button) findViewById(R.id.btn_name_clear);
		btnNameClear.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				etName.setText("");
			}
		});
		btnPasswordClear = (Button) findViewById(R.id.btn_password_clear);
		btnPasswordClear.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				etPw.setText("");
			}
		});
		etName = (EditText)findViewById(R.id.et_name);
		etName.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if(s.length() > 0){
					btnNameClear.setVisibility(View.VISIBLE);
				}else{
					btnNameClear.setVisibility(View.GONE);
				}
			}
		});
		etPw = (EditText)findViewById(R.id.et_pw);
		etPw.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if(s.length() > 0){
					btnPasswordClear.setVisibility(View.VISIBLE);
				}else{
					btnPasswordClear.setVisibility(View.GONE);
				}
			}
		});	
		
		btnLogin = (Button)findViewById(R.id.btn_login);
		
		btnLogin.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(check()){
					ProgressDialogHelper.show(mContext, "正在登录,请稍后...");
					new UserRequest(mContext, mHandler).login(etName.getText().toString(), etPw.getText().toString());
				}
			}
		});
		
		String phone = PrefUtils.getPrefString(mContext, PrefConstants.USER_PHONE, "");
		etName.setText(phone);
		
	}
	
	/**
	 * 检测条件
	 * check(这里用一句话描述这个方法的作用)
	 * (这里描述这个方法适用条件 – 可选)
	 * @return
	 * boolean
	 * @exception
	 * @since  1.0.0
	 */
	private boolean check(){
		if(StringUtil.isNull(etName.getText().toString())){
			ToastHelper.toastShort(mContext, "请输入手机号码");
			return false;
		}
		if(!StringUtil.isMobileNO(etName.getText().toString())){
			ToastHelper.toastShort(mContext, "请输入正确格式的手机号码");
			return false;
		}
		if(StringUtil.isNull(etPw.getText().toString())){
			ToastHelper.toastShort(mContext, "请输入6到16位非空格密码");
			etPw.setText("");
			return false;
		}
//		if(etPw.getText().toString().length() < 6){
//			ToastHelper.toastShort(mContext, "输入的密码长度太短,请重新输入");
//			return false;
//		}
//		if(etPw.getText().toString().length() > 16){
//			ToastHelper.toastShort(mContext, "输入的密码长度太长,请重新输入");
//			return false;
//		}
		return true;
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		switch (resultCode) {
		case 501:
			setResult(501);
			finish();
			break;

		default:
			break;
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.menu_confirm, menu);
		menu.getItem(0).setTitle("注册");
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_confirm:
			startActivityForResult(new Intent(mContext, RegisterActivity.class), 500);
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	
}
